package udpComunication;

import java.net.*;
import java.io.*;

public class UdpClient {

	public static void main(String[] args) {
		
		int receivePort = 19000;
		InetAddress afterNeighbourIP = null;
		DatagramPacket packet = null;
		DatagramSocket socket = null;
		ByteArrayInputStream biStream = null;
		DataInputStream diStream = null;
		String messaggio = null;
		
		byte[] res = null;
		
		try {
			afterNeighbourIP = InetAddress.getByName("192.168.1.100");
		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			System.out.println("Errore nella determinazione del'endpoint...");
			System.exit(1);
		} 
		
		try {
			socket = new DatagramSocket(receivePort);
			socket.setSoTimeout(30000);
			res = new byte[200];
			packet = new DatagramPacket(res, res.length,afterNeighbourIP,receivePort);
			packet.setData(res);
			System.out.println("In attesa di ricevere...creata la socket "+socket);			
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("Problemi nella creazione della socket...\n");
			System.exit(2);
		}
		
		while(true) {
		
		try {
			socket.receive(packet);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("\nProblemi nella lettura sulla socket...\n");
			System.exit(3);
		}
		
		receivePort = packet.getPort();
		afterNeighbourIP = packet.getAddress();
		res = packet.getData();

		System.out.println("Pacchetto ricevuto sulla socket...");
		System.out.println("Mittente: "+afterNeighbourIP.getHostAddress()+" sulla porta "+receivePort);
		biStream = new ByteArrayInputStream( packet.getData(),0,packet.getLength());
		diStream = new DataInputStream(biStream);
		try {
			messaggio = diStream.readUTF();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Messaggio: "+messaggio);
		
		}
		//socket.close();
		
	}
}